package dm.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import dm.config.exceptiom.BizException;
import dm.cont.ContSql;
import dm.cont.MyConfig;
import dm.model.DataDescription;
import dm.model.DataLocation;
import dm.model.FileUtiles;
import dm.model.ModelInfo;
import dm.repository.DataSetRepository;
import dm.weka.DataUtils;
import dm.weka.ModelUtils;

/**
 * RESTfulController
 */
@RestController
@RequestMapping(value = "/api")
public class RESTfulController {
	private DataSetRepository dataSetRepository;
	@Autowired
	private JdbcTemplate jdbcTemp;
	@Autowired
	private MyConfig myconfig;

	@Autowired
	public RESTfulController(DataSetRepository dataSetRepository) {
		this.dataSetRepository = dataSetRepository;
	}

	@GetMapping(value = "/data/names")
	public List<String> findAllData() {
		return dataSetRepository.findAllName();
	}

	@GetMapping(value = { "/data/desc/{name}", "/data/desc/", "/data/desc" })
	public DataDescription getDataDescription(@PathVariable(value = "name", required = false) String name,
			@CookieValue(value = "dataName", required = false) String dataName) throws Exception {

		DataLocation dataLocation = null;
		System.out.println(name);
		System.out.println(dataName);
		if (name != null) {
			dataLocation = dataSetRepository.findByName(name);
		} else if (dataName != null) {
			dataLocation = dataSetRepository.findByName(dataName);
		} else
			return null;
		if (dataLocation != null) {
			dataLocation.setPath(myconfig.getProfile() + myconfig.FILE_PATH + dataLocation.getPath().split("/")[2]);
			return DataUtils.toExplore(dataLocation);
		} else
			return null;
	}

	@RequestMapping(value = "/model/evalinfo", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelInfo getModelEvalInfo(ModelInfo modelInfo, @CookieValue("dataName") String dataName,
			HttpSession session) {
		try {
			if (modelInfo.isEmpty()) {
				System.out.println("modelInfo 为空");
				modelInfo = (ModelInfo) session.getAttribute("modelInfo");
				System.out.println(modelInfo);
			}
			if (modelInfo.isEmpty())
				return null;

			DataLocation dataLocation = dataSetRepository.findByName(dataName);
			dataLocation.setPath(myconfig.getProfile() + dataLocation.getPath());

			return ModelUtils.toEvaluate(modelInfo, dataLocation);
		} catch (Exception e) {
			new BizException("模型参数错误");
		}
		return modelInfo;
	}

	// 查看已选择数据状态
	@GetMapping(value = "/chosedata")
	public Map<String, Object> choosedDataset(@CookieValue(value = "dataName", required = false) String dataName) {
		if (dataName != null) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("chose", true);
			map.put("dataName", dataName);
			return map;
		} else {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("chose", false);
			return map;
		}
	}

	// 上传文件
	@PostMapping("/uploadFile")
	public Integer uploadFile(@Param("file") MultipartFile file) throws FileNotFoundException {
		if (file.isEmpty()) {
			return 100;
		}
		String fileName = file.getOriginalFilename();
		if (StrUtil.isEmpty(fileName)) {
			return 101;
		}
		String filename = file.getOriginalFilename().split("\\.")[0];

		String filename2 = DateUtil.format(new Date(), "YYYYMMddhhmmss") + "_" + filename;
		@SuppressWarnings("static-access")
		String outfilepath2 = myconfig.getProfile() + myconfig.FILE_PATH + filename2 + ".arff";
		String newfilename = myconfig.getProfile() + myconfig.TEMP_PATH + IdUtil.objectId() + ".csv";
		boolean res = FileUtiles.csv2Arff(file, outfilepath2, newfilename);
		if (res) {
			// 转成功就入库
			String tempname = "dataset/public/" + filename2 + ".arff";
			String sql = "INSERT dataset (id,NAME,path) VALUES(?,?,?)";
			Integer res_id = jdbcTemp.queryForObject("SELECT MAX(id) FROM dataset", Integer.class);
			jdbcTemp.update(sql, new Object[] { res_id + 1, filename2, tempname });
			return 200;
		} else {
			return 102;
		}
	}
}